package com.filter;

import com.annotation.Decrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @ Author xsd
 * @ crate time 2020/5/25 14:47
 * @ 描述  拦截器
 * zj: implements HandlerInterceptor 坐标：dispartServert __controller之前
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String url=request.getRequestURI();
        log.info("AuthSignInterceptor <====："+url);
        // 1、重复提交 2、toekn过期校验 3、签名校验
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null && modelAndView.getModel() != null && modelAndView.getModel().size() > 0) {
            Map<String, Object> dataMap = modelAndView.getModel();
            for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                Object obj = entry.getValue();
                if (obj instanceof List) {
                    List list = (List) obj;
                    list.forEach(info -> {
                        Field[] fields = info.getClass().getDeclaredFields();
                        for (Field field : fields) {
                            if (!field.isAnnotationPresent(Decrypt.class)) {
                                continue;
                            }
                            field.setAccessible(true);
                            try {
                                field.set("1111","33333333");
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
        log.info("post ...");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("after ...");
    }
}
